;;;; Created on 2008-07-24 14:50:43

(in-package :cl-user)

(load
 (merge-pathnames
  (make-pathname
   :directory '(:relative ".")
   :name "jacolib-init" :type "lisp" :case :local)
  (make-pathname 
   :directory (pathname-directory *load-truename*)
   :host (pathname-host *load-truename*)
   :device (pathname-device *load-truename*))))

;
; user' s parameters 
;

(defparameter default-host "localhost")
(defparameter default-port 40015)
(defparameter default-password "bella")

;
; *jacolib-args*
;

#+clisp
(defvar *jacolib-args* ext:*args*)
#+sbcl
(defvar *jacolib-args* (rest sb-ext:*posix-argv*))
#+cmu
(defvar *jacolib-args* (cdr (cdr (cdr extensions:*command-line-strings*))))
#-(or clisp sbcl cmu)
(defvar *jacolib-args* nil)

(defvar *host* default-host)
(defvar *port* default-port)
(defvar *secret-string* default-password)

(defvar *jacolib* (make-instance 'jacolib:jacolib))
(defvar *clsh* (jacolib:jacolib-shell *jacolib*))
(defvar *jssh* nil)

(setf (cl-log:log-manager) (make-instance 'cl-log:log-manager 
                                          :message-class 'cl-log:formatted-message))
(cl-log:start-messenger 'cl-log:text-file-messenger 
                        :filename "./jacolib-log.txt"
                        :category '(or :protocol-error :protocol-info
                                       :authentication-error :authentication-info))


(do ((args *jacolib-args* (cdr args)))
    ((null args) nil)
  (let ((arg (car args)))
    ;(format t "~A~%" args)
    (if (null *jssh*)
        (if (or
             (string= arg "h")
             (string= arg "p")
             (string= arg "s"))
            (let ((v (cadr args)))
              (setf args (cdr args))
              (if (string= arg "h")
                  (setf *host* v))
              (if (string= arg "p")
                  (setf *port* (parse-integer v)))
              (if (string= arg "s")
                  (setf *secret-string* v)))
            (progn
              (format t "launch jacolib client with arguments: ~A ~A ~A~%" *host* *port* *secret-string*)
              (setf *jssh* (jacolib:jacolib-connect *jacolib* "jssh" *host* *port* *secret-string*)))))
    (if *jssh*
        (progn
          (if (string= arg "js")
              (let ((v (cadr args)))
                (setf args (cdr args))
                (format t "JS Eval: ~A~%Result: ~A~%" v (jacolib:shell-eval *jssh* v))))
          (if (string= arg "cl")
              (let ((v (cadr args)))
                (setf args (cdr args))
                (format t "CL Eval: ~A~%Result: ~A~%" v (jacolib:shell-eval *clsh* v))))
          (if (and (string-not-equal arg "js") (string-not-equal arg "cl"))
              (format t "JS Eval: ~A~%Result: ~A~%" arg (jacolib:shell-eval *jssh* arg)))))))
          
(jacolib:remote-shell-quit *jssh*)
